package spring.cloud.tasks.executor.executor.task.execute_statistics;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Setter
@Getter
public final class ExecuteStatistics {

    private static ConcurrentMap<String, AtomicInteger> taskIdToSuccessCountMap = new ConcurrentHashMap<>();

    private static ConcurrentMap<String, AtomicInteger> taskIdToFailureCountMap = new ConcurrentHashMap<>();


    private static void incrementProcessCount(final ConcurrentMap<String, AtomicInteger> processCountMap, final String taskId) {
        processCountMap.putIfAbsent(taskId, new AtomicInteger(0));
        processCountMap.get(taskId).incrementAndGet();
    }

    private static void incrementProcessCount(final ConcurrentMap<String, AtomicInteger> processCountMap, final String taskId, final int count) {
        processCountMap.putIfAbsent(taskId, new AtomicInteger(0));
        processCountMap.get(taskId).addAndGet(count);
    }


    //

    public static synchronized void incrementProcessSuccessCount(final String taskId, final int successCount) {
        incrementProcessCount(taskIdToSuccessCountMap, taskId, successCount);
    }


    public static int getProcessSuccessCount(final String taskId) {

        return null == taskIdToSuccessCountMap.get(taskId) ? 0 : taskIdToSuccessCountMap.get(taskId).get();
    }


    public static void incrementProcessFailureCount(final String taskId, final int failureCount) {
        incrementProcessCount(taskIdToFailureCountMap, taskId, failureCount);
    }


    public static int getProcessFailureCount(final String taskId) {

        return null == taskIdToFailureCountMap.get(taskId) ? 0 : taskIdToFailureCountMap.get(taskId).get();
    }


    public static void resetSuccessFailureCount(final String taskId) {

        if (taskIdToSuccessCountMap.containsKey(taskId)) {
            taskIdToSuccessCountMap.get(taskId).set(0);
        }
        if (taskIdToFailureCountMap.containsKey(taskId)) {
            taskIdToFailureCountMap.get(taskId).set(0);
        }
    }


}
